package com.vrv.vap.baseline.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.vrv.vap.baseline.entity.AssetTypeTemplate;
import com.vrv.vap.baseline.mapper.AssetTypeTemplateMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

@Service
public class AssetTypeTemplateImportService {
    @Autowired
    private AssetTypeTemplateMapper assetTypeTemplateMapper;

    @Transactional(rollbackFor = Exception.class)
    public int importFromZip(MultipartFile file) throws IOException {
        File tempDir = Files.createTempDirectory("import_").toFile();
        try (ZipInputStream zis = new ZipInputStream(file.getInputStream())) {
            ZipEntry entry;
            while ((entry = zis.getNextEntry()) != null) {
                if (entry.getName().endsWith(".xlsx")) {
                    File excelFile = new File(tempDir, entry.getName());
                    Files.copy(zis, excelFile.toPath());
                    return importFromExcel(excelFile);
                }
            }
            throw new IOException("ZIP文件中未找到Excel文件");
        } finally {
            deleteDirectory(tempDir);
        }
    }

    private int importFromExcel(File file) {
        List<AssetTypeTemplate> successList = new ArrayList<>();

        EasyExcel.read(file, AssetTypeTemplate.class, new AnalysisEventListener<AssetTypeTemplate>() {
            @Override
            public void invoke(AssetTypeTemplate data, AnalysisContext context) {
                if (isValidData(data)) {
                    successList.add(data);
                }
            }

            @Override
            public void doAfterAllAnalysed(AnalysisContext context) {
            }
        }).sheet().doRead();

        if (!successList.isEmpty()) {
            return assetTypeTemplateMapper.insertBatch(successList);
        }
        return 0;
    }

    private boolean isValidData(AssetTypeTemplate data) {
        if (data.getAssetTypeGuid() == null || data.getAssetTypeGuid().trim().isEmpty()) {
            data.setAssetTypeGuid(UUID.randomUUID().toString());
        }
        return true;
    }

    private void deleteDirectory(File directory) {
        File[] files = directory.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    deleteDirectory(file);
                } else {
                    file.delete();
                }
            }
        }
        directory.delete();
    }
}